<template>
  <el-drawer
    v-model="visible"
    :title="drawerTitle"
    :size="width"
    :z-index="zIndex"
    append-to-body
    lock-scroll
    :close="handleBeforeClose"
    modal-class="cod-adjust-modal"
    custom-class="cod-adjust-drawer"
  >
    <!-- Header strip -->
    <div class="header-strip">
      <div class="strip-left">
        订单号：<el-tag size="small" effect="dark">{{ order.orderNo }}</el-tag>
      </div>
      <div class="strip-right" v-if="order.orderNo"></div>
    </div>

    <el-form ref="formRef" :model="form" :rules="rules" label-width="110px" class="cod-form">
      <!-- 订单信息 -->
      <div class="panel">
        <div class="panel-title">
          <el-icon><User /></el-icon>
          <span>订单信息</span>
        </div>
        <el-descriptions :column="2" border size="small" class="order-desc">
          <el-descriptions-item label="客户姓名">{{
            order.receiverName || '-'
          }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">
            <div class="inline">
              <span>{{ order.receiverPhone || '-' }}</span>
              <el-button text @click="copy(order.receiverPhone)" :disabled="!order.receiverPhone"
                >复制</el-button
              >
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">
            <span class="ellipsis" :title="order.receiverAddress">{{
              order.receiverAddress || '-'
            }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="下单日期">{{ order.orderTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="总金额">{{ fmt(order.actualPrice) }}</el-descriptions-item>
          <el-descriptions-item label="已付金额">{{ fmt(order.paidAmount) }}</el-descriptions-item>
          <el-descriptions-item label="代付金额">
            <div class="money-row">
              <el-tag type="warning">{{ fmt(order.codAmount) }}</el-tag>
              <span class="muted">（当前）</span>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 修改代付金额 -->
      <div class="panel">
        <div class="panel-title">
          <el-icon><Coin /></el-icon>
          <span>调整代付</span>
        </div>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="新的代付金额" prop="newCodAmount">
              <el-input-number
                v-model="form.newCodAmount"
                :min="0"
                :max="maxCod"
                :precision="2"
                :step="10"
                controls-position="right"
                placeholder="输入金额"
                class="w-full"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额变化">
              <div class="delta" :class="{ up: delta > 0, down: delta < 0 }">
                <el-icon v-if="delta > 0"><Top /></el-icon>
                <el-icon v-else-if="delta < 0"><Bottom /></el-icon>
                <span>{{ deltaSign }}{{ fmt(Math.abs(delta)) }}</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-alert
          v-if="form.newCodAmount > maxCod"
          type="error"
          show-icon
          :closable="false"
          title="新的代付金额不能超过『总金额 - 已付金额』"
          class="mb-12"
        />
        <el-descriptions :column="3" size="small" class="hint-desc">
          <el-descriptions-item label="可用上限">{{ fmt(maxCod) }}</el-descriptions-item>
          <el-descriptions-item label="总金额">{{ fmt(order.actualPrice) }}</el-descriptions-item>
          <el-descriptions-item label="已付金额">{{ fmt(order.paidAmount) }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 商品明细（只读） -->
      <div class="panel">
        <div class="panel-title">
          <el-icon><ShoppingBag /></el-icon>
          <span>商品明细</span>
        </div>
        <el-table :data="order.productCollection" border stripe class="goods-table" height="260">
          <el-table-column type="index" width="60" label="#" />
          <el-table-column label="商品" min-width="220">
            <template #default="{ row }">
              <div class="goods">
                <ImagePreview :src="row.productImage" width="120px" height="120px" />
                <div class="meta">
                  <div class="name">{{ row.productSpec }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="120">
            <template #default="{ row }">{{ fmt(row.actualPrice) }}</template>
          </el-table-column>
          <el-table-column prop="totalUnitNum" label="数量" width="100" />
          <el-table-column label="小计" width="140">
            <template #default="{ row }">{{ fmt(row.actualPrice * row.totalUnitNum) }}</template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 修改备注 -->
      <el-form-item label="修改备注" prop="remark" label-width="80px">
        <el-input
          v-model.trim="form.remark"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 5 }"
          maxlength="200"
          show-word-limit
          placeholder="请说明本次调额的原因，便于审计与追溯"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="footer-bar">
        <div class="summary">
          <span>新的代付金额：</span>
          <strong>{{ fmt(form.newCodAmount) }}</strong>
        </div>
        <div class="actions">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" :loading="submitting" @click="onSubmit">确 认</el-button>
        </div>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, nextTick } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { User, Coin, ShoppingBag, Top, Bottom } from '@element-plus/icons-vue';
import { useClipboard } from '../../hooks/useClipboard';

const props = withDefaults(
  defineProps<{
    width?: string | number;
    zIndex?: number;
    title?: string;
  }>(),
  {
    width: 720,
    zIndex: 4000,
    title: '修改代付金额'
  }
);

const emit = defineEmits(['close', 'confirm']);
const visible = ref(false);
const submitting = ref(false);
const formRef = ref<FormInstance>();

const order = reactive<any>({});

const form = reactive<any>({
  repurchaseOrderNo: '',
  newCodAmount: 0,
  remark: ''
});

const rules: FormRules = {
  repurchaseOrderNo: [
    { required: true, message: '请输入复购订单号', trigger: 'blur' },
    { min: 3, max: 50, message: '长度 3-50 个字符', trigger: 'blur' }
  ],
  newCodAmount: [
    { required: true, message: '请输入新的代付金额', trigger: 'change' },
    {
      validator: (_r, v, cb) => {
        if (v == null || isNaN(v)) return cb(new Error('金额需为数字'));
        if (v < 0) return cb(new Error('金额不能为负'));
        if (v > maxCod.value) return cb(new Error('不能超过可用上限'));
        cb();
      },
      trigger: ['change', 'blur']
    }
  ],
  remark: [
    { required: true, message: '请填写修改备注', trigger: 'blur' },
    { min: 2, max: 200, message: '备注 2-200 字', trigger: 'blur' }
  ]
};

// ===== Computed =====
const drawerTitle = computed(() => props.title);
// 修改代付时，计算可用的最大代付金额
const maxCod = computed(() => {
  const v = (order.actualPrice || 0) - (order.paidAmount || 0);
  return v < 0 ? 0 : Number(v.toFixed(2));
});
const delta = computed(() => Number((form.newCodAmount - (order.codAmount || 0)).toFixed(2)));
const deltaSign = computed(() => (delta.value > 0 ? '+' : delta.value < 0 ? '-' : '±'));

// ===== Methods =====
const fmt = (n?: number) => {
  const num = Number(n ?? 0);
  return `¥${num.toFixed(2)}`;
};

const { copy } = useClipboard();

const reset = () => {
  form.repurchaseOrderNo = '';
  form.newCodAmount = 0;
  form.remark = '';
};

/**
 * 对外暴露：展示抽屉
 * @param payload 完整订单对象 或 最少包含金额字段
 */
const show = async (payload: any) => {
  // 填充订单
  Object.assign(order, payload);
  // 初始化表单
  reset();
  form.newCodAmount = Number(order.codAmount || 0);

  visible.value = true;
  await nextTick();
};

const close = () => {
  visible.value = false;
  emit('close');
};

const onSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    submitting.value = true;
    try {
      // 这里调用接口提交
      // await api.updateCodAmount({...})

      emit('confirm', {
        orderId: order.id,
        repurchaseOrderNo: form.repurchaseOrderNo,
        newCodAmount: Number(form.newCodAmount),
        remark: form.remark
      });
      ElMessage.success('代付金额已更新');
      close();
    } finally {
      submitting.value = false;
    }
  });
};

const handleBeforeClose = (_: any, done: () => void) => {
  done();
};

defineExpose({ show, close });
</script>

<style lang="scss" scoped>
.cod-adjust-drawer :deep(.el-drawer__header) {
  margin-bottom: 8px;
}

.header-strip {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  margin: 0 0 12px;
  border-radius: 12px;

  .strip-left {
    display: flex;
    align-items: center;
    font-weight: 600;
    color: #747474;
    font-size: 14px;
  }
}

.cod-form {
  .panel {
    margin-bottom: 16px;
  }
  .panel-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    margin-bottom: 10px;

    color: #747474;
    font-size: 16px;
  }
  .order-desc {
    :deep(.el-descriptions__body) {
      background-color: #fff;
    }
  }
  .inline {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .ellipsis {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  .muted {
    color: #94a3b8;
    font-size: 12px;
  }
  .money-row {
    display: flex;
    align-items: center;
    gap: 6px;
  }
  .delta {
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 6px;
  }
  .delta.up {
    color: #16a34a;
  }
  .delta.down {
    color: #dc2626;
  }
  .w-full {
    width: 100%;
  }
  .mb-12 {
    margin-bottom: 12px;
  }
}

.goods-table {
  :deep(.el-table__header) th {
    background: #f8fafc;
  }
  .goods {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .thumb {
    width: 44px;
    height: 44px;
    border-radius: 8px;
    overflow: hidden;
    background: #f1f5f9;
  }
  .meta {
    display: grid;
    gap: 2px;
  }
  .name {
    font-weight: 600;
    max-width: 420px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .attrs {
    font-size: 12px;
  }
}

.footer-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 8px 4px 0;
  border-top: 1px dashed #e5e7eb;
  .summary {
    font-size: 14px;
  }
  .actions {
    display: flex;
    gap: 8px;
  }
}
</style>
